<template>
	<view class="page-fade-in" :style="{opacity: pageOpc}">
		<template v-if="pageOpc">
			<view class="circuitSetup-container flexWarpColumn">
				<!-- <view class="img-box">
					<image src="https://p6.itc.cn/images01/20210507/ed67e1d07c904e6d988c49cb4a688580.jpeg" mode="aspectFill"></image>
				</view> -->
				<view v-for="(item,index) in deviceList" :key="index">		
					<view class="device-name">{{item.device_name||'-'}}</view>
					<view class="info-box">
						<view class="info-item">
							<text class="lable">设备ID：</text>
							<text class="value">{{item.device_id}}</text>
						</view>
						<view class="info-item">
							<text class="lable">设备状态：</text>
							<view class="value">{{item.info.DeviceStatus==2?'在线':'离线'||'-'}} 
								<text class="circle" v-if="item.info.DeviceStatus==2" style="background:rgba(94, 251, 10, 1)"></text>
								<text class="circle" v-else style="background:rgba(165,42,42,1)"></text>
							</view>
						</view>
						<view class="info-item">
							<text class="lable">网络状态：</text>
							<text class="value">{{item.info.DeviceNetStatus==1?'4G在线':item.info.DeviceNetStatus==2?'wifi在线':'-'}}</text>
						</view>
						<view class="info-item">
							<text class="lable">最后一次心跳：</text>
							<text class="value">{{item.info.LastHeartTime}}</text>
						</view>
					</view>
					
					<view class="table-box">
						<view class="table-item table-head">
							<text class="serial">序号</text>
							<text class="name">名称</text>
							<text class="desk">桌台</text>
							<text class="type">类型</text>
							<text class="control">手工控制</text>
						</view>
						<view class="table-item" v-for="(val,k) in item.line_list" :key="k">
							<view class="serial">{{k+1}}</view>
							<view class="name" @tap="editName(index,val.line_name,k)">{{val.line_name}}</view>
							<view class="desk">
								<uni-data-select
								  v-model="val.equipment_id"
								  :localdata="tableRange"
								  @change="tableChange(index,k)"
								  class="data-select"
								  style="font-size: 24rpx;"
								></uni-data-select>
							</view>
							<view class="type">
								<uni-data-select
								  v-model="val.type"
								  :localdata="typeRange"
								  @change="typeChange(index,k)"
								  class="data-select"
								  style="font-size: 24rpx;"
								></uni-data-select>
							</view>
							<view class="control">
								<switch style="transform:scale(0.7)" 
								:checked="val.is_open==1&&item.isOnline" 
								:disabled="val.disabled||!item.isOnline"
								@change="switchChange(index,k)" 
								@tap="tapSwitch(item.isOnline)"/>
							</view>
						</view>
					</view>
				</view>
							
				<view class="remark" v-if="deviceList.length>0">
					备注：主控开关与订单同步通电断电，逆向开关在订单开始时断电，订单结束时通电。（常用与桌底氛围灯和包房门禁）
				</view>
				<view class="save-btn" @tap="handleSubmit"  v-if="deviceList.length>0">保存</view>
				
				<uni-popup ref="inputDialog" type="dialog" :is-mask-click="false">
					<view class="dialog-box">
						<uni-icons type="closeempty" size="20" class="close-icon" @tap="closeDialog"></uni-icons>
						<view class="title">修改名称</view>
						<input type="text" v-model="inputValue" placeholder="请输入" class="my-input" />
						<view class="btns">
							<text class="cancel" @tap="cancel">取消</text>
							<text class="sure" @tap="sure">确定</text>
						</view>
					</view>
				</uni-popup>
			</view>
		</template>
	</view>
</template>

<script>
	// 防抖函数
	function debounce(fn, wait) {
	    let timeout = null;
	    return function() {
	        let context = this;
	        let args = arguments;
	        if (timeout) clearTimeout(timeout);
	        let callNow = !timeout;
	        timeout = setTimeout(() => {
	            timeout = null;
	        }, wait);
	        if (callNow) fn.apply(context, args);
	    };
	}
	export default{
		data(){
			return{
				pageOpc:0,
				tableRange:[],
				typeRange:[
					{ value: 1, text: "主控" },
					{ value: 2, text: "逆向" },
				],
				deviceList:[],
				index:null,
				innerIndex:null,
				inputValue:'',
				first:true,
			}
		},
		onReady(){
			setTimeout(() => {
				this.pageOpc=1
			}, 100)
		},
		onLoad() {
			this.getStoreDeviceList()
			this.getTableList()
		},
		computed:{
			selected(){
				let newList = []
				this.deviceList.forEach(item=>{
					item.line_list.forEach(val=>{
						if(!(val.line_name==''&&val.type==0)){
							newList.push(val)
						}
					})
				})	
				return newList
			}
		},
		methods:{
			// 获取店铺电路设备信息
			getStoreDeviceList:debounce(function(){
				if(this.first){
					uni.showLoading({
						title:'加载中...',
						mask:true
					})
				}
				this.$request.post(this.$api.getStoreDeviceList, {
					store_id:uni.getStorageSync('store_id'),
					is_equipment:1,
				}, {
					token:true
				}).then(res => {
					let {
						data = {}
					} = res;
					if (res.code==1) {
						// console.log(data,"设备列表")
						this.deviceList=data
						this.deviceList.forEach(item=>{
							if(item.info.DeviceStatus==2){  // 设备在线
								this.$set(item,'isOnline',true)
							}else{
								this.$set(item,'isOnline',false)
							}

							let timestamp= Date.parse(item.info.LastHeartTime);
							item.info.LastHeartTime=this.$tools.formatDate(timestamp)
							item.line_list.forEach(val=>{
								// val.is_open=1
								this.$set(val,'disabled',false)
							})
						})
						
					}
				}).finally(() => {
					setTimeout(() => {
						if(this.first){
							this.$tools.hideLoading()
							this.first=false
						}
					}, 500)
				})
			},1200),
			
			// 获取桌台数据
			getTableList(){
				this.$request.post(this.$api.getTable, {
					store_id:uni.getStorageSync('store_id')
				}, {
					token:true
				}).then(res => {
					let {
						data = {}
					} = res;
					if (res.code==1) {
						// console.log(data,"桌台信息")
						data.forEach((item)=>{
							this.tableRange.push({value:item.id,text:item.equipment_name})
						})
						this.tableRange.unshift({value:0,text:'无'})
					}
				})
			},
			
			
			tableChange(index,k){
				const isDuplicate= this.hasDuplicateProperties(this.selected,'equipment_id','type','device_id')
				if (isDuplicate) {
					this.$nextTick(()=>{
						this.$tools.showToast( '同一桌台，一个类型不能重复绑定！')
						this.deviceList[index].line_list[k].equipment_id=0
					})
				}
			},
			
			typeChange(index,k){
				const isDuplicate= this.hasDuplicateProperties(this.selected,'equipment_id','type','device_id')	
				if (isDuplicate) {
					this.$nextTick(()=>{
						this.deviceList[index].line_list[k].type=0
						this.$tools.showToast( '同一桌台，一个类型不能重复绑定！')
						
					})
				}
			},
			
			hasDuplicateProperties(arr, prop1, prop2,prop3) {
			  for (let i = 0; i < arr.length; i++) {
			    for (let j = i + 1; j < arr.length; j++) {
					if (arr[i][prop1] == arr[j][prop1]&&arr[i][prop1]!=0&&arr[j][prop1]!=0 
						&& arr[i][prop2] == arr[j][prop2]&&arr[i][prop2]!=0&&arr[j][prop1]!=0 
						&& arr[i][prop3] == arr[j][prop3]) 
					{
						return true;
					}
			    }
			  }
			  return false;
			},
				
			switchChange(index,k){
				this.deviceList[index].line_list[k].disabled=true
				
				let data=this.deviceList[index].line_list[k]
				let device_id=data.device_id
				let num=data.num
				let is_open=data.is_open
				
				let way=''
				if(is_open==0){
					way=this.$api.smartOpenLamp
				}else{
					way=this.$api.smartCloseLamp
				}
				this.$request.post(way, {
					store_id:uni.getStorageSync('store_id'),
					device_id:device_id,
					num:num,
				}, {
					token:true
				}).then(res => {
					let {
						data = {}
					} = res;
					// res.code=2
					if (res.code==1) {
						this.$tools.showToast(res.msg)
						// if(is_open==0){
						// 	this.deviceList[index].line_list[k].is_open=1
						// }else{
						// 	this.deviceList[index].line_list[k].is_open=0
						// }				
						setTimeout(()=>{
							this.getStoreDeviceList()
							this.deviceList[index].line_list[k].disabled=false
						},2000)
					}
				})
			},
			
			tapSwitch(online){
				if(!online){
					this.$tools.showToast('设备不在线，请检查网络连接情况!')
				}
			},
			
			editName(index,value,k){
				this.inputValue=value
				this.index=index
				this.innerIndex=k
				this.$refs.inputDialog.open()
			},
			closeDialog(){
				this.$refs.inputDialog.close()
			},
			cancel(){
				this.closeDialog()
			},
			sure(){
				this.deviceList[this.index].line_list[this.innerIndex].line_name=this.inputValue
				this.closeDialog()
			},
			
			handleSubmit(){
				let data=[]
				this.deviceList.forEach(item=>{
					item.line_list.forEach(val=>{
						if(!(val.line_name==''&&val.type==0)){
							data.push({
								id:val.id,
								line_name:val.line_name,
								equipment_id:val.equipment_id||0,
								type:val.type||0
							})
						}
					})
				})
				// console.log(data,"kkkkkkkkkkk")
				// console.log(JSON.stringify(data),"kkkkkkkkkkk")
				
				this.$request.post(this.$api.setLineInfo, {
					store_id:uni.getStorageSync('store_id'),
					data:JSON.stringify(data)
				}, {
					token:true
				}).then(res => {
					let {
						data = {}
					} = res;
					if (res.code==1) {
						this.$tools.showToast('设置成功')
						this.getStoreDeviceList()
					}
				})
			}
		
		}
	}
</script>

<style lang="scss" scoped>
	.circuitSetup-container{
		padding: 20rpx;
		gap: 30rpx;
		.img-box{
			width: 100%;
			height: 380rpx;
			border-radius: 16rpx;
			overflow: hidden;
		}
		.device-name{
			// margin-top: 20rpx;
			padding: 16rpx 20rpx;
			font-size: 32rpx;
			color: #fff;
			border-bottom: 1rpx solid rgba(255, 255, 255,0.5);
		}
		.info-box{
			margin-top: 20rpx;
			padding: 0 20rpx;
			overflow:auto;
			.info-item{
				margin-bottom: 10rpx;
				font-size: 30rpx;
				display: flex;
				.lable{
					color:rgba(255, 255, 255, 0.9);
				}
				.value{
					color:rgba(255, 255, 255, 1);
					display: flex;
					align-items: center;
					gap: 10rpx;
					.circle{
						width: 26rpx;
						height: 26rpx;
						border-radius: 50%;
						// background: rgba(94, 251, 10, 1);
					}
				}
			}
		}
		
		/deep/.table-box{
			background: #1D1C5C;
			margin-top: 20rpx;
			.table-head{
				>text{
					padding: 16rpx 0;
					font-weight: bold;
				}
			}
			.table-item{
				display: flex;
				border-bottom: 1rpx solid rgba(255,255,255,0.5);
				color:#fff;
				text-align: center;
				font-size: 24rpx;
				&:nth-child(2n){
					background: #353484;
				}
				&:last-child{
					border: unset;
				}
				>text,>view{
					flex-shrink: 0;
					// padding: 10rpx 0;
					display: flex;
					justify-content: center;
					align-items: center;
				}
				.serial{
					width: 9%;
					border-right: 1rpx solid rgba(255,255,255,0.5);
				}
				.name{
					width:25%;
					border-right: 1rpx solid rgba(255,255,255,0.5);
				}
				.desk{
					width:30%;
					border-right: 1rpx solid rgba(255,255,255,0.5);
				}
				.type{
					width:20%;
					border-right: 1rpx solid rgba(255,255,255,0.5);
					.uni-select__selector{
						width: 200rpx !important;
					}
				}
				.control{
					width:15%;
				}
				.data-select{
					font-size: 24rpx;
					width:100%;
					.uni-select{
						height: 50rpx;
						border: unset;
						.uni-select__input-box{
							height: 100%;
							overflow: hidden;
							.uni-select__input-text{
								font-size: 24rpx;
								color: #fff;
							}
							.uniui-clear{
								font-size: 40rpx !important;
							}
							
						}
						.uni-select__selector{
							width: 400rpx;
							left: 50%;
							transform: translateX(-50%);
							.uni-popper__arrow_bottom{
								left: 50%;
								transform: translateX(-50%);
							}
							.uni-select__selector-empty, .uni-select__selector-item{
								color: #333;
								font-size: 26rpx;
								padding: 10rpx;
							}
						}
						
					}
				}
			}
		}
		.remark{
			margin: 0 auto;
			margin-top: 20rpx;
			padding: 0 10rpx;
			color:#fff;
			font-size: 22rpx;
			font-weight: bold;
		}
		.save-btn{
			width: 670rpx;
			height: 80rpx;
			margin: 0 auto;
			margin-top: 30rpx;
			background:rgba(31, 124, 247, 1) ;
			border-radius: 72rpx;
			font-weight: 500;
			font-size: 36rpx;
			color: #FFFFFF;
			display: flex;
			justify-content: center;
			align-items: center;
		}
		
		.dialog-box{
			width: 600rpx;
			padding: 40rpx;
			box-sizing: border-box;
			background: #fff;
			border-radius: 16rpx;
			position: relative;
			.close-icon{
				position: absolute;
				top:10rpx;
				right: 20rpx;
			}
			.title{
				font-size: 30rpx;
				font-weight: bold;
				text-align: center;
				letter-spacing: 2rpx;
				margin-bottom: 50rpx;
			}
			.my-input{
				border: 2rpx solid #999;
				border-radius: 8rpx;
				padding: 10rpx 20rpx;
				font-size: 28rpx;
			}
			.btns{
				margin-top: 60rpx;
				display: flex;
				justify-content: center;
				gap: 100rpx;
				text{
					width: 100rpx;
					padding: 10rpx 20rpx;
					border-radius: 8rpx;
					font-size: 28rpx;
					letter-spacing: 2rpx;
					
					text-align: center;
				}
				.cancel{
					border: 2rpx solid #999;
				}
				.sure{
					color: #fff;
					background: rgb(39, 91, 184);
				}
			}
		}
	}
</style>